<?php

namespace app\apiadmin\service\live;

use app\apiadmin\model\action\ActionModel;
use app\apiadmin\service\statics\LiveUserGetDataService;
use app\apiadmin\service\statics\MongoDbService;
use app\common\utils\Res;
use Firebase\JWT\JWT;
use Predis\Client;
use think\facade\Config;
use think\facade\Db;
use think\facade\Log;

class SiyuAppService
{

    /**  @var Client redis */
    private $redis;
    /** @var MongoDbService */
    private $_mongodb;
    /**
     * 直播管理
     */
    public function __construct($config = [], Client $redis = null)
    {
        $this->redis = $redis;
    }
    //获取播放信息
    public static function getPlayInfo($param){
        if(!$param['code']){
            return Res::error('code不存在');
        }
        $code = self::encrypt($param['code'],'D');
        $live_manager = Db::table('xh_siyu_live_manager')->where('id',$code)->field('status,end_time,push_file_name,teacher_id')->find();
        if(!$live_manager){
            return Res::error('code错误');
        }
        if($live_manager['status'] !=2){
            return Res::error('该直播尚未结束');
        }
        if((strtotime($live_manager['end_time']) + 48*3600) < time()){
            return Res::error('该链接已超时');
        }
        $teacher = Db::table('xh_siyu_teacher')->where('id',$live_manager['teacher_id'])->field('img,name')->find();
        
        $play_info = DB::table('xh_siyu_files')->where('http_urls',$live_manager['push_file_name'])->field('fileID,appID,playKey')->find();
        if($play_info && $play_info['appID'] && $play_info['fileID'] && $play_info['playKey']){
            $currentTime = time();
            $psignExpire = $currentTime + 48*3600; // 可任意设置过期时间，示例48小时内有效
            $playKey = $play_info['playKey'];
            $payload = array(
                "appId" => intval($play_info['appID']),
                "fileId" => $play_info['fileID'],
                "contentInfo" => array(
                    "audioVideoType"=> 'Original',
                    "rawAdaptiveDefinition"=> 10, // 允许输出的未加密的自适应码流模板 ID
                    "imageSpriteDefinition"=> 10    // 进度条预览的雪碧图模板 ID
                ),
                "currentTimeStamp" => $currentTime,
                "expireTimeStamp" => $psignExpire, // 可任意设置过期时间，示例1h  $currentTime + 3600
            );
            $psign = JWT::encode($payload, $playKey, 'HS256');  //签名
            $data = [];
            $data['appID'] = $play_info['appID'];
            $data['fileID'] = $play_info['fileID'];
            $data['psign'] = $psign;
            $data['teacher_name'] = $teacher?$teacher['name']:'';
            $data['teacher_img'] = $teacher?$teacher['img']:'';
            return Res::ok($data);
        }else{
            return Res::error('文件信息不存在');
        }
        
    }
    
    //$string：需要加密解密的字符串；$operation：判断是加密还是解密，E表示加密，D表示解密；$key：密匙。
    public static function encrypt($string,$operation,$key=''){
        
        $key = $key ?: 'ceeffe0-1028-840e-dce9-d41634d54cff';
        //$key = $key ?: Config::get('domain.app_key');
        $key_length=strlen($key);
        $string=$operation=='D'?base64_decode(str_replace(array('-', '_'), array('+', '/'), $string)):substr(md5($string.$key),0,8).$string;
//        $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string;
        $string_length=strlen($string);
        $rndkey=$box=array();
        $result='';
        for($i=0;$i<=255;$i++){
            $rndkey[$i]=ord($key[$i%$key_length]);
            $box[$i]=$i;
        }
        for($j=$i=0;$i<256;$i++){
            $j=($j+$box[$i]+$rndkey[$i])%256;
            $tmp=$box[$i];
            $box[$i]=$box[$j];
            $box[$j]=$tmp;
        }
        for($a=$j=$i=0;$i<$string_length;$i++){
            $a=($a+1)%256;
            $j=($j+$box[$a])%256;
            $tmp=$box[$a];
            $box[$a]=$box[$j];
            $box[$j]=$tmp;
            $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
        }
        if($operation=='D'){
            if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)){
                return substr($result,8);
            }else{
                return'';
            }
        }else{
            return str_replace('=','',str_replace(array('+', '/', '='), array('-', '_'), base64_encode($result)));
//            return str_replace('=','',base64_encode($result));
        }
    }
    
//     //加密
//    public static function encrypt($data, $key = ''){
//        $key = $key ?: Config::get('domain.app_key');
//        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
//        $encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv);
//        return base64_encode($encrypted . '::' . $iv);
//    }
//    // 解密
//    public static function decrypt($data, $key = ''){
//        $key = $key ?: Config::get('domain.app_key');
//        list($encryptedData, $iv) = explode('::', base64_decode($data), 2);
//        return openssl_decrypt($encryptedData, 'aes-256-cbc', $key, 0, $iv);
//    }

}
